﻿using System;
using System.Collections.Generic;
using System.Reflection;
using Vbyte.Extension;

namespace Vbyte.Configuration
{
    /// <summary>
    /// JSON数据绑定路径配置
    /// </summary>
    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Property, AllowMultiple = false, Inherited = true)]
    public class JSONPathAttribute : Attribute
    {
        /// <summary>
        /// 获取JSON路径配置
        /// </summary>
        /// <param name="jsonPath">JSON对象路径</param>
        public JSONPathAttribute(string jsonPath)
        {
            JsonPath = jsonPath;
        }

        /// <summary>
        /// JSON对象路径名称
        /// </summary>
        public string JsonPath { get; set; }

        /// <summary>
        /// 获取实例对象上json路径与属性的映射配置
        /// </summary>
        /// <param name="instanceType">实例类型</param>
        /// <returns>如果有映射配置则返回映射配置词典，否则为空项的词典对象。</returns>
        public static Dictionary<string, string> GetMappingDict(Type instanceType)
        {
            Dictionary<string, string> dict = new Dictionary<string, string>();
            JSONPathAttribute currentAttr;
            foreach (PropertyInfo pi in instanceType.GetProperties())
            {
                JSONPathAttribute[] attrs = pi.GetMemberInfoCustomAttributes<JSONPathAttribute>(true);
                if (attrs.Length > 0)
                {
                    currentAttr = attrs[0];
                    dict[currentAttr.JsonPath] = pi.Name;
                }
            }
            return dict;
        }

    }
}
